'''
登录页面所有事件信号管理
'''
import json
import threading

import requests
from PyQt5.QtCore import QObject, pyqtSlot, pyqtSignal, QUrl
from PyQt5.QtWebChannel import QWebChannel
from PyQt5.QtWebEngineWidgets import QWebEngineView

import cache
from dao.commonDao import CommonDao
from protoc import IMProto_pb2
from tcp.tcpClient import TcpClient


class LoginAction(QObject):

    #登录结果信号
    loginResultSig = pyqtSignal(int)

    def __init__(self):
        super().__init__()
        self.loginResultSig.connect(self.loginResultNotify)

    #登录线程
    def login_(self,username,password):
        if (username == '' or password == ''):
            self.loginResultSig.emit(-1)
            return
        else:
            header = {'clientOs': '1'}
            try:
                r = requests.post('http://localhost:8080/walala-api/user/login',
                                  data={'username': username, 'password': password}
                                  , headers=header)
                if r.status_code is not 200:
                    self.loginResultSig.emit(-2)
                    return
                else:
                    try:
                        result = json.loads(r.text)
                        print(result)
                        if result['code'] is 0:
                            # 将用户token缓存起来，并发起长连接
                            cache.Cache.userInfo = result['data']

                            # 登录成功，创建db
                            cache.Cache.dao = CommonDao(cache.Cache.userInfo['id'])

                            _thread = threading.Thread(target=self.socketLogin)
                            _thread.setDaemon(True)
                            _thread.start()
                        else:
                            self.loginResultSig.emit(result['code'])
                    except Exception as e:
                        print(e)
                        self.loginResultSig.emit(-3)
                        return
            except Exception as e:
                print(e)
                print('服务接口不可用')
                self.loginResultSig.emit(-2)
                return

    #登录
    @pyqtSlot(str, str,result=str)
    def login(self, username, password):
        cache.Cache.threadPool.submit(self.login_(username,password))

    def socketLogin(self):
        instance = TcpClient.getInstance()
        instance.start('192.168.56.1',8001)

    @pyqtSlot()
    def send(self):
        TcpClient.getInstance().send()

    #登录结果信号槽
    def loginResultNotify(self,resultCode):
        pass

#发送tcp登录包
def sendTcpLoginPack():
    userId = cache.Cache.userInfo['id']
    token = cache.Cache.userInfo['token']
    userLogin = IMProto_pb2.UserLogin()
    userLogin.userId = userId
    userLogin.token = token
    msgBody = userLogin.SerializeToString()
    from tcp.tcpClient import Package
    pack = Package()
    pack.cmd = 1
    pack.msgBody = msgBody
    pack.receiverId = 0
    pack.ack = 0
    from tcp.tcpClient import TcpClient
    TcpClient.getInstance().send(pack)

def createLogin():
    channel = QWebChannel()
    loginAction = LoginAction()
    channel.registerObject('loginObject', loginAction)
    view = QWebEngineView()
    view.setFixedWidth(300)
    view.setFixedHeight(400)
    print ("22222")
    view.load(QUrl('file:///Users/momo/PycharmProjects/walala-client/ui/html/login.html'))
    print("3333")
    view.page().setWebChannel(channel)
    view.show()
    # cache.Cache.app.processEvents()
    print("44444")